<template>
    <div>
        <el-card shadow="never">
            <div slot="header" class="edu-page-title">
                <span>{{ $t('information.contentMaintenance') }}</span>
            </div>
            <el-form
                :model="infoForm"
                ref="infoForm"
                :disabled="mode !== 'edit'"
                label-width="120px"
                :rules="rules"
            >
                <el-row :gutter="24">
                    <el-col :span="8">
                        <el-form-item label="开始时间：" prop="beginTime">
                            <el-date-picker
                                type="date"
                                v-model="infoForm.beginTime"
                                style="width: 100%"
                                placeholder="请选择"
                                format="yyyy/MM/dd"
                                :picker-options="pickerOptions"
                                value-format="yyyy/MM/dd"
                            ></el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="结束时间：" prop="endTime">
                            <el-date-picker
                                type="date"
                                v-model="infoForm.endTime"
                                style="width: 100%"
                                placeholder="请选择"
                                format="yyyy/MM/dd"
                                :picker-options="pickerOptionsofEnd"
                                value-format="yyyy/MM/dd"
                            ></el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="面向用户：" prop="userOriented">
                            <el-select
                                multiple
                                style="width: 100%"
                                v-model="infoForm.userOriented"
                                filterable
                                collapse-tags
                                title="请选择面向用户，不勾选默认全校"
                                placeholder="请选择面向用户，不勾选默认全校"
                            >
                                <el-option
                                    v-for="(opt, index) in options.userOriedtedList"
                                    :key="index"
                                    :label="opt.label"
                                    :value="opt.value"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="24" v-if="hideStatus">
                    <el-col :span="8">
                        <el-form-item label="是否弹屏：" prop="isPopup">
                            <YesNoSelect
                                v-model="infoForm.isPopup"
                                labelAll="请选择"
                                :showAll="false"
                            ></YesNoSelect>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="是否置顶：" prop="isSetTop">
                            <YesNoSelect
                                v-model="infoForm.isSetTop"
                                labelAll="请选择"
                                :showAll="false"
                            ></YesNoSelect>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="置顶失效时间：" prop="setTopInvalidTime">
                            <el-date-picker
                                type="date"
                                :disabled="infoForm.isSetTop == 0"
                                v-model="infoForm.setTopInvalidTime"
                                style="width: 100%"
                                placeholder="请选择"
                                format="yyyy/MM/dd"
                                :picker-options="pickerOptionsofEnd"
                                value-format="yyyy/MM/dd"
                            ></el-date-picker>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-form-item label="公告标题：" prop="title">
                        <el-input v-model="infoForm.title" placeholder="请输入"></el-input>
                    </el-form-item>
                </el-row>
                <el-row>
                    <el-form-item label="公告正文：" prop="content">
                        <tinymce ref="editor" :setting="editorSetting" v-model="infoForm.content" />
                    </el-form-item>
                </el-row>
                <el-row>
                    <el-form-item label="上传文件：">
                        <el-upload
                            :headers="{ 'X-Token': $store.state.session.sessionid }"
                            :data="{ bucketname: 'face', folderpath: 'file' }"
                            action="/api/commonservice/obsfile/uploadfile"
                            :on-success="handleUploadSuccess"
                            :on-remove="handleFileRemove"
                            :on-error="handlerError"
                            :on-preview="handlerPre"
                            :file-list="infoFileList"
                            class="upload-demo"
                            multiple
                        >
                            <el-button class="operate-add" type="primary">选择文件</el-button>
                        </el-upload>
                    </el-form-item>
                </el-row>
                <el-row v-if="mode == 'edit'">
                    <el-form-item class="text-right">
                        <el-button @click="cancel">取消</el-button>
                        <el-button type="primary" @click="saveInfo">保存</el-button>
                    </el-form-item>
                </el-row>
            </el-form>
        </el-card>
        <el-dialog title="提示" :visible.sync="saveDialogVisible" :show-close="false" width="35%">
            <span>{{ contentTip }}</span>
            <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="gotoMyInformation">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import Tinymce from 'common/src/components/tinymce/editor'
import {
    addPublicMsg,
    updatePublicMsg,
    getPublicMsgDetail,
    getGroupUserList,
    findTopCommonMsgPublish
} from 'common/src/api/public/information'
import Bus from 'common/src/utils/bus'

export default {
    name: '',
    components: {
        tinymce: Tinymce
    },
    data: function() {
        let that = this
        return {
            pickerOptions: {
                // 今天及以后的日期
                disabledDate(time) {
                    return time.getTime() < Date.now() - 8.64e7
                }
            },
            editorSetting: {
                height: 200
            },
            infoForm: {
                title: '',
                beginTime: '',
                endTime: '',
                isPopup: '0',
                isSetTop: '0',
                setTopInvalidTime: '',
                userOriented: [],
                userOrientedName: [],
                status: '1',
                content: '',
                commonAttachmentList: []
            },
            options: {
                userOriedtedList: []
            },
            contentTip: '',
            saveDialogVisible: false,
            infoFileList: [],
            rules: {
                title: [
                    {
                        required: true,
                        message: '请填写公告标题',
                        trigger: ['blur', 'change']
                    }
                ],
                beginTime: [
                    {
                        required: true,
                        message: '请选择开始时间',
                        trigger: ['blur', 'change']
                    }
                ],
                endTime: [
                    {
                        required: true,
                        message: '请选择结束时间',
                        trigger: ['blur', 'change']
                    }
                ],
                isPopup: [
                    {
                        required: true,
                        message: '请选择是否弹屏',
                        trigger: ['blur', 'change']
                    }
                ],
                isSetTop: [
                    {
                        required: true,
                        message: '请选择是否置顶',
                        trigger: ['blur', 'change']
                    }
                ],
                setTopInvalidTime: [
                    {
                        required: false,
                        message: '请选择置顶失效时间',
                        trigger: ['blur', 'change']
                    }
                ],
                userOriented: [
                    {
                        required: false,
                        message: '请选择面向用户',
                        trigger: ['blur', 'change']
                    }
                ],
                content: [
                    {
                        required: true,
                        message: '请填写公告正文',
                        trigger: ['blur', 'change']
                    }
                ]
            }
        }
    },
    props: {
        mode: {
            type: String,
            default: 'edit'
        },
        infoId: {
            type: String | Number,
            default: ''
        },
        hideStatus: {
            type: Boolean,
            default: true
        }
    },
    computed: {
        pickerOptionsofEnd(val) {
            if (this.infoForm.beginTime) {
                let that = this
                if (
                    new Date(this.formatTime(this.infoForm.beginTime)) >
                    new Date(this.formatTime(this.infoForm.endTime))
                ) {
                    this.infoForm.endTime = ''
                }
                return {
                    disabledDate(time) {
                        return (
                            time.getTime() <=
                            new Date(that.formatTime(that.infoForm.beginTime)).getTime()
                        )
                    }
                }
            } else {
                return {
                    disabledDate(time) {
                        return time.getTime() < Date.now() - 8.64e7
                    }
                }
            }
        }
    },
    watch: {
        'infoForm.isSetTop'(val) {
            this.resetInvalidTime(val)
        }
    },
    created() {
        this.getOptions()
    },
    methods: {
        handleFileRemove(file, fileList) {
            this.infoFileList = fileList
            this.infoForm.commonAttachmentList = this.setInformationAttachList(fileList)
        },
        handleUploadSuccess(res, file, fileList) {
            this.infoFileList = fileList
            this.infoForm.commonAttachmentList = this.setInformationAttachList(fileList)
        },
        //上传文件失败回调
        handlerError(rresponse, file, fileList) {
            this.$message({
                message: '上传失败,请稍后再试！',
                type: 'error'
            })
        },
        handlerPre(file){
            window.location.href =
                "/api/commonservice/obsfile/downloadfile?objectkey=" + file.url;
        },
        setInformationAttachList(fileList) {
            let attachList = []
            let fileNameReg = /^(.+\\)?([^\.\\]+(\..+)?)$/
            let name = ''
            attachList = fileList.map(item => {
                if (item.response && item.response.data) {
                    let key = Object.keys(item.response.data)[0]
                    const uploadedObj = item.response.data[key]
                    let attachObj = {}
                    if (uploadedObj) {
                        if (fileNameReg.test(uploadedObj.fileName)) {
                            name = RegExp.$2
                        }
                        attachObj.fileName = name
                        attachObj.fileLacation = uploadedObj.objectkey
                    }
                    return attachObj
                } else {
                    let attachObj = {}
                    if (fileNameReg.test(item.name)) {
                        name = RegExp.$2
                    }
                    attachObj.fileName = name
                    attachObj.fileLacation = item.url
                    return attachObj
                }
            })
            return attachList
        },
        cancel() {
            this.$emit('backToList', 1)
        },
        saveInfo() {
            let _this = this
            _this.$refs.infoForm.validate(valid => {
                if (!valid) {
                    return
                }
                const topStatusCheckbox = _this.infoForm.topStatus
                _this.infoForm.topStatus = topStatusCheckbox ? '1' : '0'
                let {
                    status,
                    title,
                    endTime,
                    content,
                    commonAttachmentList,
                    beginTime: startTime,
                    isPopup: popStatus,
                    isSetTop: topStatus,
                    setTopInvalidTime: invalidTopTime,
                    userOriented
                } = _this.infoForm
                let faceUser = []
                let faceUserName = []
                if (userOriented.length) {
                    userOriented.forEach(item => {
                        let index = _.findIndex(_this.options.userOriedtedList, it => {
                            return it.value === item
                        })
                       index >-1 && faceUserName.push(_this.options.userOriedtedList[index].label)
                    })
                } else {
                    userOriented = []
                    faceUserName = ['全校']
                }
                let queryParams = {
                    status,
                    title,
                    endTime,
                    content,
                    commonAttachmentList,
                    startTime,
                    popStatus,
                    topStatus,
                    invalidTopTime,
                    faceUser: userOriented.join(','),
                    faceUserName: faceUserName.join('|')
                }
                findTopCommonMsgPublish().then(res => {
                    if (res.code !== 200) {
                        _this.$confirm(res.msg, '提示', {
                            confirmButtonText: '确定',
                            cancelButtonText: '取消',
                            type: 'warning'
                        })
                            .then(() => {
                                if (_this.infoId) {
                                    queryParams.id = _this.infoId
                                    updatePublicMsg(queryParams).then(res => {
                                        if (res.code == 200) {
                                            _this.handleSavedSuccess()
                                        }
                                    })
                                } else {
                                    addPublicMsg(queryParams).then(res => {
                                        if (res.code == 200) {
                                            _this.handleSavedSuccess()
                                        }
                                    })
                                }
                            })
                            .catch(() => {})
                    } else {
                        if (_this.infoId) {
                            queryParams.id = _this.infoId
                            updatePublicMsg(queryParams).then(res => {
                                if (res.code == 200) {
                                    _this.handleSavedSuccess()
                                }
                            })
                        } else {
                            addPublicMsg(queryParams).then(res => {
                                if (res.code == 200) {
                                    _this.handleSavedSuccess()
                                }
                            })
                        }
                    }
                })
            })
        },
        handleSavedSuccess() {
            this.contentTip = '信息公告已保存，可前往我的信息发布中编辑或提交审核'
            this.saveDialogVisible = true
        },
        gotoMyInformation: function() {
            this.saveDialogVisible = false
            // 回到列表页面
            this.$emit('backToList', 1)
        },
        formatTime(time) {
            return time.slice(0, 10).replace(/-/g, '/')
        },
        handlegetPublicMsgDetail(id) {
            getPublicMsgDetail(id).then(res => {
                let {
                    title,
                    endTime,
                    content,
                    commonAttachmentList,
                    startTime: beginTime,
                    popStatus: isPopup,
                    topStatus: isSetTop,
                    invalidTopTime: setTopInvalidTime,
                    faceUser: userOriented
                } = res.data
                this.infoForm = {
                    title,
                    endTime: this.formatTime(endTime),
                    content,
                    commonAttachmentList,
                    beginTime: this.formatTime(beginTime),
                    isPopup,
                    isSetTop,
                    setTopInvalidTime: setTopInvalidTime ? this.formatTime(setTopInvalidTime) : '',
                    userOriented: userOriented ? userOriented.split(',') : ''
                }
                this.$set(this.infoForm, 'endTime', this.formatTime(endTime))
                this.resetInvalidTime(isSetTop)
                this.infoFileList = this.getInformationAttachList(res.data.commonAttachmentList)
            })
        },
        resetInvalidTime(val) {
            this.rules.setTopInvalidTime[0].required = val == 1 ? true : false
            if (val == 0) {
                this.infoForm.setTopInvalidTime = ''
            }
        },
        getInformationAttachList(fileList) {
            let attachList = []
            fileList.forEach(item => {
                const attachObj = {}
                attachObj.name = item.fileName
                attachObj.url = item.fileLacation
                attachList.push(attachObj)
            })
            return attachList
        },
        getOptions() {
            getGroupUserList().then(res => {
                if (res.code === 200) {
                    if (res && res.data) {
                        this.setSelectOpt(res.data)
                    }
                    // 查询当前信息
                    if (this.infoId) {
                        this.handlegetPublicMsgDetail(this.infoId)
                    }
                }
            })
        },
        setSelectOpt(data) {
            this.setOptFn('userOriedtedList', data)
        },
        setOptFn(type, data) {
            data.forEach(item => {
                this.options[type].push({
                    value: item.groupId + '',
                    label: item.groupName
                })
            })
        }
    }
}
</script>

<style lang="scss" scoped>
.information-page {
    .el-date-editor.el-input {
        width: 100%;
    }
    .el-select {
        width: 100%;
    }
}
.upload-card {
    margin-top: 10px;
}
.footer-wrapper {
    width: 100%;
    background: #fff;
    padding: 15px 0;
    .btn-list {
        text-align: right;
    }
}
</style>
